#include <stdio.h>
#include <iostream>
#include <Windows.h>

HINSTANCE hInst;

extern "C" {
	BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved){
		switch(fdwReason){
			case DLL_PROCESS_ATTACH:
			//當這個DLL被映射到了進程的地址空間時
				if(!hInst)
				{
					hInst = LoadLibraryA("AntiVC.dll");//載入AntiVC.dll
				}
			break;

			case DLL_THREAD_ATTACH:
			//一個線程正在被創建

			break;

			case DLL_THREAD_DETACH:
			//線程終結

			break;

			case DLL_PROCESS_DETACH:
			//這個DLL從進程的地址空間中解除映射
				typedef void (CALLBACK* LPFreeCds)();
				LPFreeCds FreeAllCdsFile = (LPFreeCds)GetProcAddress(hInst, "FreeAllCdsFile");
				FreeAllCdsFile();
			break;
		}
		return(TRUE);
	}
}


JNIEXPORT jint JNICALL Java_LoadCdsFromBuffer
  (JNIEnv * env, jclass jc, jbyteArray FileBuffer, jint FileBufLen, jstring Password)
{
	if(!hInst)
	{
		hInst = LoadLibraryA("AntiVC.dll");//載入AntiVC.dll

		if(!hInst)
		{
			return -2;
		}
	}
	
	typedef int (CALLBACK* LPLoadCds)(char[],int,char[]);
	LPLoadCds LoadCdsFromBuffer = (LPLoadCds)GetProcAddress(hInst, "LoadCdsFromBuffer");

	char* buf = jbyteArrayTostring(env, FileBuffer);
	char* cpassword = jstringTostring(env,Password);

	int index = LoadCdsFromBuffer (buf,FileBufLen,cpassword);//載入識別庫

	return index;
}

JNIEXPORT jint JNICALL Java_LoadCdsFromFile
  (JNIEnv* env, jclass jc, jstring FilePath, jstring Password)
{
	if(!hInst)
	{
		hInst = LoadLibraryA("AntiVC.dll");//載入AntiVC.dll

		if(!hInst)
		{
			return -2;
		}
	}
	char* cfilepath = jstringTostring(env,FilePath);
	char* cpassword = jstringTostring(env,Password);
	typedef int (CALLBACK* LPLoadCds)(char[],char[]);
	LPLoadCds LoadCdsFromFile = (LPLoadCds)GetProcAddress(hInst, "LoadCdsFromFile");
	int index = LoadCdsFromFile (cfilepath,cpassword);//載入識別庫

	return index;
}

JNIEXPORT jstring JNICALL Java_GetVcodeFromBuffer
  (JNIEnv* env, jclass jc, jint CdsFileIndex, jbyteArray ImgBuffer, jint ImgBufLen)
{
	if(!hInst)
	{
		return stringTojstring(env,"");
	}

	char* buf = jbyteArrayTostring(env, ImgBuffer);
	char result[20];

	typedef bool (CALLBACK* LPGetVcode)(int,char*,int,char[]);
	LPGetVcode GetVcodeFromBuffer = (LPGetVcode)GetProcAddress(hInst, "GetVcodeFromBuffer");
	if(GetVcodeFromBuffer(CdsFileIndex,buf,ImgBufLen,result))
		return stringTojstring(env,result);
	else
		return stringTojstring(env,"");
}

JNIEXPORT jstring JNICALL Java_GetVcodeFromFile
  (JNIEnv * env, jclass jc, jint CdsFileIndex, jstring FilePath)
{
	if(!hInst)
	{
		return stringTojstring(env,"");
	}

	char* cfilepath = jstringTostring(env,FilePath);
	char result[20];

	typedef bool (CALLBACK* LPGetVcode)(int,char[],char[]);
	LPGetVcode GetVcodeFromFile = (LPGetVcode)GetProcAddress(hInst, "GetVcodeFromFile");
	if(GetVcodeFromFile(CdsFileIndex,cfilepath,result))
		return stringTojstring(env,result);
	else
		return stringTojstring(env,"");
}



